package com.thd.springboot.framework.redis.configuration;

import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Jedis配置，项目启动注入JedisPool
 */
@Configuration
@ConditionalOnProperty(name = "spring.redis.jedis.pool.max-active",matchIfMissing=false)
public class JedisConfig {

    /**
     * logger
     */
    private static final Logger logger = LoggerFactory.getLogger(JedisConfig.class);
    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.password}")
    private String password;
    @Value("${spring.redis.timeout}")
    private int timeout;
    @Value("${spring.redis.database}")
    private int database;

    @Value("${spring.redis.jedis.pool.max-active}")
    private int maxActive;

    @Value("${spring.redis.jedis.pool.max-wait}")
    private int maxWait;

    @Value("${spring.redis.jedis.pool.max-idle}")
    private int maxIdle;

    @Value("${spring.redis.jedis.pool.min-idle}")
    private int minIdle;




//    @Bean
//    public JedisCluster jedisCluster() {
//        try {
//            String[] hosts = host.split(",");
//            Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
//            for(String h:hosts){
//                String ip = h.split(":")[0].trim();
//                int port  = Integer.parseInt(h.split(":")[1].trim());
//                jedisClusterNode.add(new HostAndPort(ip, port));
//                logger.info("JedisCluster集群设置，当前节点为: {}:{}", ip, port);
//            }
//            return new JedisCluster(jedisClusterNode, 1000, 1000, 5, new GenericObjectPoolConfig<>());
//        } catch (Exception e) {
//            logger.error("初始化Redis连接池JedisPool异常:{}", e.getMessage());
//        }
//        return null;
//    }


    @Bean
    public JedisPool redisPoolFactory()  throws Exception{
        System.out.println("创建JedisPool");
        System.out.println("redis地址：" + host + ":" + port);
        System.out.println("redis database：" + database);
        System.out.println("reids pool maxIdle：" + maxIdle);
        System.out.println("reids pool minIdle：" + minIdle);
        System.out.println("reids pool maxWait：" + maxWait);
        System.out.println("reids pool maxActive：" + maxActive);
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();



        //控制一个pool可分配多少个jedis实例，通过pool.getResource()来获取；
        //如果赋值为-1，则表示不限制；如果pool已经分配了maxActive个jedis实例，则此时pool的状态为exhausted(耗尽)。
        jedisPoolConfig.setMaxTotal(maxActive);

        //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例。
        jedisPoolConfig.setMaxIdle(maxIdle);

        //控制一个pool最少有多少个状态为idle(空闲的)的jedis实例。如果pool中空闲数少于改配置,则创建,用于方式使用的时候可以用现成的链接
        jedisPoolConfig.setMinIdle(minIdle);

        //表示当borrow(引入)一个jedis实例时，最大的等待时间，如果超过等待时间，则直接抛出JedisConnectionException；单位毫秒
        //小于零:阻塞不确定的时间,  默认-1
        jedisPoolConfig.setMaxWaitMillis(maxWait);

        // 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
//        jedisPoolConfig.setBlockWhenExhausted(blockWhenExhausted);
        // 是否启用pool的jmx管理功能, 默认true
        jedisPoolConfig.setJmxEnabled(true);


        //connectionTimeout 连接超时（默认2000ms）
        //soTimeout 响应超时（默认2000ms）
//        (GenericObjectPoolConfig poolConfig, String host, int port, int timeout, String password, int database) {
        JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout,password,database);

        return jedisPool;
    }
}
